package synchronicity.ui;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;

import synchronicity.calendar.Calendar;
import synchronicity.calendar.Calendar.ModifyCalendarFailedException;
import synchronicity.util.Range;
import ui.DisplayContext;
import ui.Screen;

/**
 * Adds an event to this host's calendar only.
 */
public class AddSingleEventScreen extends Screen {
	private static AddSingleEventScreen instance;

	private DateField start, end;

	private TextField title;

	private AddSingleEventScreen(DisplayContext display) {
		super(display);
		container = new Form("Add an event to this calendar");
		start = new DateField("Start date", DateField.DATE_TIME);
		end = new DateField("End date", DateField.DATE_TIME);
		title = new TextField("Title","",35,TextField.ANY);
		container.append(title);
		container.append(start);
		container.append(end);
	}

	private Form container;

	public synchronized static AddSingleEventScreen getInstance(
			DisplayContext display) {
		if (instance == null)
			instance = new AddSingleEventScreen(display);
		return instance;
	}

	protected Command[] getCommands() {
		return getDefaultCommands();
	}

	protected Displayable getDisplayable() {
		return container;
	}

	protected String getTitle() {
		return "Synchronicity";
	}

	public void commandAction(Command arg0, Displayable arg1) {
		if (arg0.getCommandType() == Command.OK) {
			Calendar cal = getContext().getHost().getCalendar();
			Range dateRange = new Range(start.getDate().getTime(), end
					.getDate().getTime());
			String title = this.title.getString();
			try {
				cal.addCalendarItem(dateRange, title);
			} catch (ModifyCalendarFailedException e) {
				System.err.println("Unable to add to calendar");
			}
			switchScreen(HomeScreen.getInstance(getContext()));
		} else if (arg0.getCommandType() == Command.CANCEL) {
			switchScreen(HomeScreen.getInstance(getContext()));
		}
	}
}
